package cn.wubo.dynamic.schedule;

import cn.wubo.sql.util.ExecuteSqlUtils;
import cn.wubo.sql.util.ModelSqlUtils;
import cn.wubo.sql.util.annotations.Table;
import com.alibaba.fastjson2.JSONObject;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class DataExchangeToTable {

    public void run() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        HttpClientBuilder clientBuilder = HttpClients.custom();

        //调整了这里
        CloseableHttpClient httpClient = clientBuilder.setConnectionManager(PoolingHttpClientConnectionManagerBuilder
                .create().setSSLSocketFactory(sslsf).build()).build();

        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30000);
        httpRequestFactory.setConnectTimeout(30000);
        //httpRequestFactory.setReadTimeout(30000);

        httpRequestFactory.setHttpClient(httpClient);

        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);

        try (Connection conn = DriverManager.getConnection("jdbc:h2:file:./data/demo;AUTO_SERVER=TRUE", "sa", "")) {
            if (Boolean.FALSE.equals(ExecuteSqlUtils.isTableExists(conn, "data_exchange")))
                ModelSqlUtils.createSql(new DataExchange()).createTable(conn);
            //runShanghai(restTemplate, conn);
            //runBeijing(restTemplate,conn);
            //runGuangzhou(restTemplate,conn);
            //runZhejiang(restTemplate, conn);
            //runShenzhen(restTemplate, conn);
            //runHainan(restTemplate, conn);
            //runXibu(restTemplate, conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    private void runShanghai(RestTemplate restTemplate, Connection conn) {
        String[] sectorNames = new String[]{"金融", "航运交通", "综合", "贸易", "先进制造", "国际"};
        Arrays.stream(sectorNames).forEach(sectorName -> runShanghaiSector(restTemplate, conn, sectorName));

    }

    private void runShanghaiSector(RestTemplate restTemplate, Connection conn, String sectorName) {
        Integer pageNum = 1;

        JSONObject params = new JSONObject();
        params.put("search", "");
        params.put("type", "list");
        params.put("sectorName", sectorName);
        params.put("firstSubSectorName", "");
        params.put("pageSize", 10);
        params.put("order", null);
        params.put("corpus", "");
        params.put("pageNum", pageNum);
        JSONObject jo = restTemplate.postForObject("https://nidts.chinadep.com/dex-es/query/search", params, JSONObject.class);

        if (jo.getInteger("code") == 200) {
            pageNum = jo.getJSONObject("data").getInteger("totalPage");
            runShanghaiSectorSave(conn, sectorName, jo);

            for (int i = 2; i <= pageNum; i++) {
                params.put("pageNum", i);
                JSONObject jo1 = restTemplate.postForObject("https://nidts.chinadep.com/dex-es/query/search", params, JSONObject.class);
                runShanghaiSectorSave(conn, sectorName, jo1);
            }
        }
    }

    private void runShanghaiSectorSave(Connection conn, String sectorName, JSONObject jo) {
        jo.getJSONObject("data").getJSONArray("list").forEach(o -> {
            JSONObject jo1 = JSONObject.from(o);
            DataExchange dataExchange = new DataExchange();
            dataExchange.setSite("上海数据交易所");
            dataExchange.setSeriesName(sectorName);
            dataExchange.setDataName(jo1.getString("dataName"));
            dataExchange.setDataContent(jo1.getString("dataContent"));
            String dataType = jo1.getString("dataType");
            dataExchange.setDataType("01".equals(dataType) ? "数据集" : ("02".equals(dataType) ? "数据服务" : "数据应用"));
            dataExchange.setSupplierCompanyName(jo1.getString("supplierCompanyName"));
            ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
        });
    }

    private void runBeijing(RestTemplate restTemplate, Connection conn) {
        JSONObject params = new JSONObject();
        params.put("productType", null);
        params.put("industry", null);
        params.put("viewCode", 1);
        params.put("pageSize", 10000);
        params.put("pageNum", 1);
        JSONObject jo = restTemplate.postForObject("https://webs.bjidex.com/api/dstp/data-asset-server/dataProduct/deal/list", params, JSONObject.class);
        if (jo.getInteger("code") == 200) {
            jo.getJSONObject("data").getJSONArray("list").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("北京国际大数据交易所");
                dataExchange.setSeriesName(jo1.getString("industry"));
                dataExchange.setDataName(jo1.getString("productName"));
                dataExchange.setDataContent(jo1.getString("productIntroduction"));
                dataExchange.setDataType(jo1.getString("productTypeName"));
                dataExchange.setSupplierCompanyName(jo1.getString("orgName"));
                if (jo1.containsKey("unitPrice")) dataExchange.setPrice(jo1.getDouble("unitPrice"));
                if (jo1.containsKey("setracemoneyName")) dataExchange.setOtherPrice(jo1.getString("setracemoneyName"));
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }

    }


    private void runGuangzhou(RestTemplate restTemplate, Connection conn) {
        JSONObject jo = restTemplate.getForObject("https://www.gzdex.com.cn/apaas/serviceapp/v3/servicemarket/dataShop/list?page=1&size=10000", JSONObject.class);
        if (jo.getInteger("success") == 1) {
            jo.getJSONArray("data").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("贵阳大数据交易所");
                dataExchange.setSeriesName(jo1.getString("sectors_name"));
                dataExchange.setDataName(jo1.getString("name"));
                dataExchange.setDataContent(jo1.getString("descript"));
                dataExchange.setDataType(jo1.getString("data_service_type1_name") + "-" + jo1.getString("service_type_name"));
                dataExchange.setSupplierCompanyName(jo1.getString("enterprise_name"));
                if (jo1.containsKey("prod_price")) dataExchange.setPrice(jo1.getDouble("prod_price"));
                if (jo1.containsKey("prod_price_unit")) dataExchange.setOtherPrice(jo1.getString("prod_price_unit"));
                dataExchange.setTradeCount(jo1.getInteger("apply_num"));
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }
    }

    private void runZhejiang(RestTemplate restTemplate, Connection conn) {
        JSONObject params = new JSONObject();
        params.put("timestamp", System.currentTimeMillis());
        params.put("pageSize", 10000);
        params.put("pageNum", 1);
        JSONObject jo = restTemplate.postForObject("https://ditm.zjdex.com/tsslapi/product/list/guest", params, JSONObject.class);
        if (jo.getString("code").equals("SUCCESS")) {
            jo.getJSONObject("data").getJSONArray("list").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("浙江大数据交易中心");
                dataExchange.setSeriesName(jo1.getString("productCategoryName"));
                dataExchange.setDataName(jo1.getString("name"));
                dataExchange.setDataContent(jo1.getString("description"));
                dataExchange.setDataType(jo1.getString("productTypeName"));
                dataExchange.setSupplierCompanyName(jo1.getString("providerCompanyName"));
                dataExchange.setOtherPrice(jo1.getString("displayPrice"));
                dataExchange.setDataSourceType(jo1.getString("dataSourceName"));
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }
    }

    private void runShenzhen(RestTemplate restTemplate, Connection conn) {
        Map<String, String> map = new HashMap<>();
        map.put("工业制造", "02024031116463217900000101710102");
        map.put("金融服务", "02024031116464040700000101710104");
        map.put("现代农业", "02024031116464823200000101710106");
        map.put("商贸流通", "02024031116465555900000101710108");
        map.put("交通运输", "02024031116540913700000101710117");
        map.put("科技创新", "02024031116541784800000101710119");
        map.put("文化旅游", "02024031116542611700000101710121");
        map.put("医疗健康", "02024031116543333800000101710124");

        map.entrySet().stream().forEach(entry -> runShenzhenDetail(restTemplate, conn, entry));
    }

    private void runShenzhenDetail(RestTemplate restTemplate, Connection conn, Map.Entry<String, String> entry) {
        JSONObject params = new JSONObject();
        params.put("cxlx", "01");
        params.put("pageSize", 10000);
        params.put("pageNo", 1);
        params.put("yylyIdList", Collections.singleton(entry.getValue()));

        JSONObject jo = restTemplate.postForObject("https://www.szdex.com/dmall/v1.0/sjsp/spgl/pageQueryMhSjsp", params, JSONObject.class);
        if (jo.getInteger("code") == 200) {
            jo.getJSONObject("data").getJSONArray("rows").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("深圳数据交易所");
                dataExchange.setSeriesName(entry.getKey());
                dataExchange.setDataName(jo1.getString("spMc"));
                dataExchange.setDataContent(jo1.getString("spms"));
                dataExchange.setDataType(jo1.getString("spsjlxMc"));
                dataExchange.setSupplierCompanyName(jo1.getString("fbfQyMc"));
                String price = jo1.getString("xsjg");
                if("面议".equals(price))
                    dataExchange.setOtherPrice(price);
                else
                    dataExchange.setPrice(Double.valueOf(price));
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }
    }

    private void runHainan(RestTemplate restTemplate, Connection conn) {
        Map<String, String> dataTypeMaps = new HashMap<>();
        dataTypeMaps.put("data_service", "产品服务");
        dataTypeMaps.put("data_analysis_report", "产品分析报告");
        dataTypeMaps.put("data_report", "产品报表");
        dataTypeMaps.put("data_model", "算法模型");
        dataTypeMaps.put("general_app", "通用软件");
        dataTypeMaps.put("other", "其他");
        dataTypeMaps.put("point_service", "驻点服务");

        Map<String, String> industryTypeMaps = new HashMap<>();
        industryTypeMaps.put("4f70e3bff987eed986df4dd941e0bbaf", "农、林、牧、渔业");
        industryTypeMaps.put("6c81ec3b0911506fa3c2540dfdf4c795", "采矿业");
        industryTypeMaps.put("872c9287c6d47d1e777200b3bde9d19a", "制造业");
        industryTypeMaps.put("ed3e750a82336caf79f506c7210c40fc", "电力、热力、燃气及水生产和供应业");
        industryTypeMaps.put("1fea75deac97b01671e54a71c1477951", "建筑业");
        industryTypeMaps.put("d25d160e738d832cb52448beb30ce585", "交通运输、仓储和邮政业");
        industryTypeMaps.put("6da5a33a959f67b6d33a7256126cba8f", "信息传输、软件和信息技术服务业");
        industryTypeMaps.put("5de2731f3f111b7969e4d22f91b11561", "批发和零售业");
        industryTypeMaps.put("d7a2b682cb974778e2a7a2bb211b0c29", "住宿和餐饮业");
        industryTypeMaps.put("57d5e08e8e5e6d7dc09aa5b478f7aa5c", "金融业");
        industryTypeMaps.put("adbfd2943ddedf4ffdee6abe610825fd", "房地产业");
        industryTypeMaps.put("fd2f53323aa809b1531458322d220fa4", "租赁和商务服务业");
        industryTypeMaps.put("8575bdc6ef45c49e3475badb5346a81d", "科学研究和技术服务业");
        industryTypeMaps.put("c7eb10447dec90ff6212d91801173967", "水利、环境和公共设施管理业");
        industryTypeMaps.put("be8896468595c7eeadf4aa382a6249c3", "居民服务、修理和其他服务业");
        industryTypeMaps.put("951d360695f48281874c5c9bff141081", "教育");
        industryTypeMaps.put("6f4b340c869f5397d7b7450092d33a46", "卫生和社会工作");
        industryTypeMaps.put("614f12fea396b601dd4966e6c960bb90", "文化、体育和娱乐业");
        industryTypeMaps.put("8c30bb9bdfdb567c42fa52550ad90504", "公共管理、社会保障和社会组织");

        Map<String, String> tagTypeMaps = new HashMap<>();
        tagTypeMaps.put("ccb6fc51d06e5d415880e45ca33dda62", "科技创新");
        tagTypeMaps.put("8332177477683e45e61c10574a2f5d84", "财税金融");
        tagTypeMaps.put("e26b321652cff7137edcc05f36790417", "数据报表");
        tagTypeMaps.put("2096d989860ca04f11a0534b4a242d26", "机构团体");
        tagTypeMaps.put("dbe57b9365f689be3f88de656f00f680", "法律服务");
        tagTypeMaps.put("193a17ec55179fec6161c628956a0b22", "市场监管");
        tagTypeMaps.put("4999e0026a944a856816b93577553bc2", "资源能源");
        tagTypeMaps.put("be2cd3fa4ae0ec315adbc20dceb77a1f", "安全生产");
        tagTypeMaps.put("b1ec971383cd85bd937957acafc41cc7", "生活服务");
        tagTypeMaps.put("cb701df2d236c74ec81caf7aaaf0b0ce", "信用服务");
        tagTypeMaps.put("56003d9302fb2acd6cfd0d5c2a6e41c1", "气象服务");
        tagTypeMaps.put("e9fb70e1e36341125be4ced762167676", "教育文化");
        tagTypeMaps.put("78d9c91591d6dcf220c22916641ec20a", "社保就业");
        tagTypeMaps.put("395c6be1ed6a507d19cdeb048a27bb5f", "社会救助");
        tagTypeMaps.put("3e873a545621f374b05a5441e68525ed", "商贸流通");
        tagTypeMaps.put("d1ef8c9e9725ce62fc080498144a7824", "城建住房");
        tagTypeMaps.put("773080ca7fbacc62f3526b66544b727f", "医疗卫生");
        tagTypeMaps.put("6ca1fdd92337fc3134f0da7197c8279e", "新冠疫苗");
        tagTypeMaps.put("da0d02760d32ccff71a17db920c21f5b", "生态环境");
        tagTypeMaps.put("8ea9da66cd805db5d732b572b86efa4c", "工业农业");
        tagTypeMaps.put("c7ac74d489dff8aa8a127cb0d7c2df87", "交通运输");
        tagTypeMaps.put("2cb21cab4a5f97bb0066490faf7f2939", "地理空间");
        tagTypeMaps.put("b571df05dec36d635a93ce67e62e08d8", "其他");

        industryTypeMaps.entrySet().stream().forEach(industryEntry -> {
            tagTypeMaps.entrySet().stream().forEach(tagEntry -> runHainan(restTemplate, conn, industryEntry, tagEntry, dataTypeMaps));
        });

    }

    private void runHainan(RestTemplate restTemplate, Connection conn, Map.Entry<String, String> industryEntry, Map.Entry<String, String> tagEntry, Map<String, String> dataTypeMaps) {
        JSONObject params = new JSONObject();
        params.put("timestamp", System.currentTimeMillis());
        params.put("index", 0);
        params.put("pageNo", 1);
        params.put("pageSize", 10000);

        JSONObject paging = new JSONObject();
        paging.put("current", 1);
        paging.put("size", 10000);
        paging.put("total", 0);

        params.put("paging", paging);
        params.put("industry", industryEntry.getKey());
        params.put("tag", tagEntry.getKey());

        JSONObject jo = restTemplate.postForObject("https://www.datadex.cn/api/resource/searchBy", params, JSONObject.class);
        if (jo.getInteger("code") == 0) {
            jo.getJSONObject("data").getJSONArray("list").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("海南省数据产品超市");
                dataExchange.setSeriesName(industryEntry.getValue() + "-" + tagEntry.getValue());
                dataExchange.setDataName(jo1.getString("proResourceName"));
                dataExchange.setDataContent(jo1.getString("proResourceDesc"));
                dataExchange.setDataType(dataTypeMaps.get(jo1.getString("proResourceType")));
                dataExchange.setSupplierCompanyName(jo1.getString("companyName"));
                String itemPrice = jo1.getString("itemPrice");
                if ("-1.00".equals(itemPrice)) dataExchange.setOtherPrice("面议");
                else dataExchange.setPrice(Double.parseDouble(itemPrice) / 100);
                dataExchange.setTradeCount(jo1.getInteger("applyCount"));
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }
    }

    private void runXibu(RestTemplate restTemplate, Connection conn) {
        Map<String, String> map = new HashMap<>();
        map.put("1", "电商类");
        map.put("2", "航旅类");
        map.put("3", "建筑类");
        map.put("4", "能源类");
        map.put("5", "通信类");
        map.put("6", "信用类");
        map.put("7", "医药类");
        map.put("9", "汽车类");
        map.put("10", "农业类");
        map.put("8", "其他类");

        map.entrySet().stream().forEach(entry -> runXibuDetail(restTemplate, conn, entry));
    }

    private void runXibuDetail(RestTemplate restTemplate, Connection conn, Map.Entry<String, String> entry) {
        JSONObject params = new JSONObject();
        params.put("orderField", "publishTime");
        params.put("sortOrder", "desc");
        params.put("dataDomain", entry.getKey());
        params.put("pageNum", 1);
        params.put("pageSize", 10000);

        JSONObject jo = restTemplate.postForObject("https://trade-operator.westdex.com.cn/dop/market/goods/list", params, JSONObject.class);
        if (jo.getInteger("code") == 10000) {
            jo.getJSONObject("data").getJSONObject("data").getJSONArray("result").forEach(o -> {
                JSONObject jo1 = JSONObject.from(o);
                DataExchange dataExchange = new DataExchange();
                dataExchange.setSite("西部数据交易中心");
                dataExchange.setSeriesName(entry.getValue());
                dataExchange.setDataName(jo1.getString("goodsName"));
                dataExchange.setDataContent(jo1.getString("introduce"));
                dataExchange.setDataType(jo1.getString("goodsTypeName"));
                dataExchange.setSupplierCompanyName(jo1.getString("supplyCompanyName"));
                if (jo1.containsKey("price")) {
                    dataExchange.setPrice(jo1.getDouble("price"));
                    dataExchange.setOtherPrice(jo1.getString("priceUnit"));
                } else {
                    dataExchange.setOtherPrice(jo1.getString("chargeTypeName"));
                }
                ModelSqlUtils.insertSql(dataExchange).executeUpdate(conn);
            });
        }
    }

    @Table(value = "data_exchange")
    public static class DataExchange {
        private String site;
        private String seriesName;
        private String dataName;
        private String dataContent;
        private String dataType;
        private String dataSourceType;
        private String supplierCompanyName;
        private Double price;
        private String otherPrice;
        private Integer tradeCount;

        public String getSite() {
            return site;
        }

        public void setSite(String site) {
            this.site = site;
        }

        public String getSeriesName() {
            return seriesName;
        }

        public void setSeriesName(String seriesName) {
            this.seriesName = seriesName;
        }

        public String getDataName() {
            return dataName;
        }

        public void setDataName(String dataName) {
            this.dataName = dataName;
        }

        public String getDataContent() {
            return dataContent;
        }

        public void setDataContent(String dataContent) {
            this.dataContent = dataContent;
        }

        public String getDataType() {
            return dataType;
        }

        public void setDataType(String dataType) {
            this.dataType = dataType;
        }

        public String getDataSourceType() {
            return dataSourceType;
        }

        public void setDataSourceType(String dataSourceType) {
            this.dataSourceType = dataSourceType;
        }

        public String getSupplierCompanyName() {
            return supplierCompanyName;
        }

        public void setSupplierCompanyName(String supplierCompanyName) {
            this.supplierCompanyName = supplierCompanyName;
        }

        public Double getPrice() {
            return price;
        }

        public void setPrice(Double price) {
            this.price = price;
        }

        public String getOtherPrice() {
            return otherPrice;
        }

        public void setOtherPrice(String otherPrice) {
            this.otherPrice = otherPrice;
        }

        public Integer getTradeCount() {
            return tradeCount;
        }

        public void setTradeCount(Integer tradeCount) {
            this.tradeCount = tradeCount;
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        new DataExchangeToTable().run();
    }
}